package com.jml.固定窗口计数器;

import java.util.concurrent.atomic.AtomicInteger;

public class JmlCounter {
    /**
     * 限流次数
     */
    private Integer limiter;
    /**
     * 计数器限流间隔的时间，在limiterTime时间范围内，只能有limiter多个请求
     */
    private Integer limiterTime;
    /**
     * 记录调用的次数
     */
    private AtomicInteger atomicInteger;

    /**
     * 记录每次重置的时间
     */
    private Long startTime;

    public JmlCounter(Integer limiter, Integer limiterTime) {
        this.limiter = limiter;
        this.limiterTime = limiterTime;
        this.atomicInteger = new AtomicInteger(1);
        startTime = System.currentTimeMillis();
    }

    public boolean tryAcquire() {
        // 1.获取系统的时间
        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis - startTime > limiterTime) {
            //  重置
            atomicInteger.set(1);
            startTime = System.currentTimeMillis();
        }
        // 如果在时间内 判断调用的次数是否 超过限流的次数
        int count = atomicInteger.get();
        if (count > limiter) {
            // 被限流了
            return false;
        }
        // 原子类+++
        atomicInteger.incrementAndGet();
        return true;
    }

    public static void main(String[] args) throws InterruptedException {
        JmlCounter jmlCounter = new JmlCounter(2, 10000);
        for (int i = 0; i < 20; i++) {
            boolean result = jmlCounter.tryAcquire();
            System.out.println(result);
        }
        System.out.println("------------------");
        Thread.sleep(10000);
        for (int i = 0; i < 20; i++) {
            boolean result = jmlCounter.tryAcquire();
            System.out.println(result);
        }
    }
}
